package com.atguigu.tingshu.user.service.strategy.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component("1002")  //指定Bean对象ID，跟发货时货物类型一致的
public class TrackPaidRecordStrategy implements PaidRecordStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 处理声音发货逻辑
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("[用户服务]处理声音发货逻辑");
        //2.处理虚拟物品发货-声音
        //2.1 根据订单编号查询已购声音表判断是否处理过该笔订单
        LambdaQueryWrapper<UserPaidTrack> trackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        trackLambdaQueryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(trackLambdaQueryWrapper);
        if (count > 0) {
            return;
        }
        //2.2 如果没有则新增用户购买声音记录
        //根据声音ID查询声音记录，获取专辑ID
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        for (Long paidTrackId : userPaidRecordVo.getItemIdList()) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(paidTrackId);
            userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
